<?php
namespace Qwadmin\Controller;

class BillsController extends ComController{
    /**
     * 我的结算单
     */
    public function mine(){
		$status = htmlspecialchars(I("status" , ''));
		$page = I("p", 1, 'intval');
		
		$status_int = 1;
		if($status == 'withdrawing'){//提现中状态
			$status_int = 2;
		}else if($status == 'paid'){//已打款
			$status_int = 3;
		}
		$pram = [
            'page'      =>  $page,
            'status'   	=>  $status_int,
			'uid'		=>  session('uid')
        ];
		$data = D("Income")->getbills($pram);
        $pagebar = new \Think\Page($data['count'], 10);
		foreach($data['list'] as $key=>$value){
			$data['list'][$key]['num'] = $value['basic_success_num']+$value['vip_success_num'];
			$data['list'][$key]['income'] = sprintf('%.2f', $value['money']*($value['proportion']/100));
			$data['list'][$key]['money'] = sprintf('%.2f', $value['money']);
		}
		
		//获取用户的数据
		$member_money = $this->USER;
		
		//用户总收益
		$member_money['income'] = sprintf('%.2f', $member_money['money']);
		$member_money['total_money'] = sprintf('%.2f', $member_money['total_money']);
		//提现中
		$member_money['income_cash'] = M('member_bills')->where(['refid'=>session('uid'),'status'=>2])->sum('income');
		if(empty($member_money['income_cash'])){
			$member_money['income_cash'] =0;
		}
		$member_money['income_cash'] = sprintf('%.2f', $member_money['income_cash']);
		
		//已打款
		$member_money['income_play'] = sprintf('%.2f', $member_money['total_income']-$member_money['money']-$member_money['income_cash']);
		
		//结算总额
		$member_money['total_bills'] = sprintf('%.2f', $member_money['total_income']);
		//申请总额
		$member_money['total_apply'] = sprintf('%.2f', $member_money['income_play']+$member_money['income_cash']);
		
		$this->assign("data", $data['list']);
        $this->assign("page", $pagebar->show());
		$this->assign("count", $data['count']);
		$this->assign("member_money", $member_money);
		$this->assign("status", $status);
        $this->display();
    }
    
    /**
     *  提现申请
     */
    public function cash_apply(){
		
		//获取可提现的金额
        $member_money = $this->USER;
		if(bccomp($member_money['money'],10)<0){
			die(json_encode(['status'=>0,'msg'=>'余额满 10 元才能提现','title'=>'提现要求未满足']));
		}
		die(json_encode(['status'=>1,'msg'=>"可提现金额 ". sprintf('%.2f',$member_money['money']) ." , 是否确定提现？",'title'=>'提现申请']));
    }
	/**
     *  提现确认
     */
    public function cash_confirm(){
		
		//获取可提现的金额
        $member_money = M('member')->field('account_type,truename,alipay,money')->where(['uid'=>session('uid')])->find();
		if(bccomp($member_money['money'],10)<0){
			die(json_encode(['status'=>0,'msg'=>'余额满 10 元才能提现','title'=>'提现要求未满足']));
		}
		//获取需要提现的所有账单日期
		$member_bills_list = M('member_bills')->field('id,bills_date,income')->where(['status'=>1,'refid'=>session('uid')])->select();
		$remarks ='';
		$income =0;
		foreach($member_bills_list as $value){
			$remarks.=$value['id'].'<br>';
			$income+=$value['income'];
		}
		if(bccomp($member_money['money'],$income)!=0){
			die(json_encode(['status'=>0,'msg'=>'账单对账有误，不可提现！','title'=>'账单错误']));
		}
		
		//开始写入提现日志
        $out_biz_no = createOrderId();
        $data =  [
            'uid'       => session('uid'),
            'amount'    => sprintf('%.2f',$member_money['money']),
			'account_type'    => $member_money['account_type'],
            'alipay'    => $member_money['alipay'],
            'realname'  => $member_money['truename'],
            'out_biz_no'    => $out_biz_no,
			'remarks'	=>  $remarks,
            'create_time'   => date('Y-m-d H:i:s'),
            'status'        => 0
        ];
		
		
		//开启事务
		M('WithdrawLog')->startTrans();
        $WithdrawLog_ret = D("WithdrawLog")->add_log($data);
        //余额相应的减除掉
        $Member_ret = D("Member")->setDecAmount(session('uid') , sprintf('%.2f',$member_money['money']));
		//账单状态修改
		$member_bills_ret = M('member_bills')->where(['status'=>1,'refid'=>session('uid')])->save(['status'=>2]);
		
		if ($WithdrawLog_ret && $Member_ret && $member_bills_ret) {//事务完成
			M('WithdrawLog')->commit();
			die(json_encode(['status'=>1,'msg'=>'提现申请成功！','title'=>'提现确认']));
		} else {//回滚
			M('WithdrawLog')->rollback();
			die(json_encode(['status'=>1,'msg'=>'提现申请失败，请重新申请！','title'=>'提现确认']));
		}
    }
    
	/**
	* 代理结算
	**/
	public function affiliate_bills(){
		$status = htmlspecialchars(I("status" , ''));
		$page = I("p", 1, 'intval');
		
		$start_date = htmlspecialchars(I("start_date", ''), ENT_NOQUOTES);
        $end_date = htmlspecialchars(I("end_date", ''), ENT_NOQUOTES);
		$agent_id = I("agent_id", 0, 'intval');

		$status_int = 'yesterday';//默认昨日
		if($status == 'search'){
			$status_int = $status;
		}
		//获取其所有下级代理
		$uid_ret = M('member')->field('uid,user,proportion')->where(['pid'=>session('uid')])->select();
		$uid_arr = [];
		$user_arr = [];
		foreach($uid_ret as $value){
			$uid_arr[] = $value['uid'];
			$user_arr[$value['uid']]=$value['user'];
		}
		if(count($uid_arr)==0){
			$uid_arr = [0];
		}
		$pram = [
            'page'      =>  $page,
			'uid'		=>  empty($agent_id)?$uid_arr:$agent_id 
        ];
		$today = strtotime(date('Y-m-d', time()));
		$yesterday = strtotime(date('Y-m-d', strtotime("-1 day")));
		if($status == 'search'){//搜索
			if (!empty($end_date)) {
				//检查日期是否有效
				list($y, $m, $d) = explode('-', $end_date);
				if (checkdate($m, $d, $y)) {
					if(strtotime($end_date)>$today){
						$start_date=date('Y-m-d',$yesterday);
						$end_date = date('Y-m-d',$today);
					}
				} else {
					$end_date = '';
				}
			}
			if (!empty($start_date)) {
				//检查日期是否有效
				list($y, $m, $d) = explode('-', $start_date);
				if (checkdate($m, $d, $y)) {
					if(strtotime($start_date) >= $end_date){
						$start_date=date('Y-m-d',$yesterday);
					}
				} else {
					$start_date = '';
				}
			}
		}
		if(empty($start_date) && empty($end_date) || $status == 'yesterday'){//昨日
			$start_date = date('Y-m-d', $yesterday);
            $end_date = date('Y-m-d',$today);
		}
		
		$pram["start_date"] = strtotime($start_date);
		$pram["end_date"] = strtotime($end_date);
		
		$data = D("Income")->getbills($pram);
        $pagebar = new \Think\Page($data['count'], 10);
		foreach($data['list'] as $key=>$value){
			$data['list'][$key]['num'] = $value['basic_success_num']+$value['vip_success_num'];
			$data['list'][$key]['income'] = sprintf('%.2f', $value['money']*($value['proportion']/100));
			$data['list'][$key]['money'] = sprintf('%.2f', $value['money']);
			$data['list'][$key]['user'] = $user_arr[$value['refid']];
		}
		$Income_data = D("Income")->getbills_count($pram);
		//
		
		$this->assign("Income_data", $Income_data);
		$this->assign("data", $data['list']);
        $this->assign("page", $pagebar->show());
		$this->assign("count", $data['count']);
		$this->assign("agent", $user_arr);
		$this->assign("status", $status);
		$this->assign("agent_id", $agent_id);
		$this->assign("start_date", $start_date);
        $this->assign("end_date", $end_date);
        $this->display();
	}
	
	/**
	* 代理结算 今日数据
	**/
	public function affiliate_bills_today(){
		$page = I("p", 1, 'intval');
		$agent_id = I("agent_id", 0, 'intval');

		//获取其所有下级代理
		$uid_ret = M('member')->field('uid,user,proportion')->where(['pid'=>session('uid')])->select();
		$uid_arr = [];
		$user_arr = [];
		$pram = [
            'page'      =>  $page,
        ];
		//默认查询当前的数据
        $start_date = date('Y-m-d',time());
        $end_date = date('Y-m-d', strtotime("+1 day"));
		
		$pram["start_date"] = strtotime($start_date);
		$pram["end_date"] = strtotime($end_date);
		$data['list'] = [];
		$Income_data = [
							'total_money' =>0,
							'success_num' =>0,
							'total_income'=>0,
							'total_member_income'=>0,
							'total_member_money'=>0
						];
		foreach($uid_ret as $value){
			$uid_arr[] = $value['uid'];
			$user_arr[$value['uid']]=$value['user'];
			$Income_s_data = D("Income")->Income_sel($value['uid'],$pram["start_date"],$pram["end_date"]);
			$data['list'][]=[
								'bills_date'=>$pram["start_date"],
								'user'=>$value['user'],
								'num'=>$Income_s_data['vip_success_num']+$Income_s_data['basic_success_num'],
								'money'=>sprintf('%.2f', $Income_s_data['money']),
								'income'=>sprintf('%.2f', $Income_s_data['money']*($value['proportion']/100)),
								'proportion'=>$value['proportion'],
							];
			$Income_data['total_money']+=$Income_s_data['money'];
			$Income_data['success_num']+=$Income_s_data['vip_success_num']+$Income_s_data['basic_success_num'];
			$Income_data['total_income']+=$Income_s_data['money']*($value['proportion']/100);
		}
		
		$Income_data['total_member_money']=$Income_s_data['money']*($this->USER['proportion']/100);
		$Income_data['total_member_income']=sprintf('%.2f', $Income_data['total_member_money']-$Income_data['total_income']);
		$Income_data['total_money']=sprintf('%.2f', $Income_data['total_money']);
		$Income_data['total_income']=sprintf('%.2f', $Income_data['total_income']);
		$Income_data['total_member_money']=sprintf('%.2f', $Income_data['total_member_money']);
		
		//
		$pagebar = new \Think\Page(count($uid_arr), count($uid_arr));
		$this->assign("Income_data", $Income_data);
		$this->assign("data", $data['list']);
        $this->assign("page", $pagebar->show());
		$this->assign("count", $data['count']);
		$this->assign("agent", $user_arr);
		$this->assign("status", 'today');
		$this->assign("agent_id", $agent_id);
		$this->assign("start_date", $start_date);
        $this->assign("end_date", $end_date);
        $this->display('affiliate_bills');
	}
	
	/**
	* 渠道结算
	**/
	public function channels_bills(){
		$status = htmlspecialchars(I("status" , ''));
		$page = I("p", 1, 'intval');
		
		$start_date = htmlspecialchars(I("start_date", ''), ENT_NOQUOTES);
        $end_date = htmlspecialchars(I("end_date", ''), ENT_NOQUOTES);
		$agent_id = I("agent_id", 0, 'intval');

		$status_int = 'today';//默认今日
		if($status == 'yesterday'){//昨日
			$status_int = $status;
		}
		//获取其所有下级代理
		$uid_ret = M('member')->field('uid,user,proportion')->where(['level'=>3])->select();
		$uid_arr = [];
		$user_arr = [];
		foreach($uid_ret as $value){
			$uid_arr[] = $value['uid'];
			$user_arr[$value['uid']]=$value['user'];
		}
		if(count($uid_arr)==0){
			$uid_arr = [0];
		}
		$pram = [
            'page'      =>  $page,
			'uid'		=>  empty($agent_id)?$uid_arr:$agent_id 
        ];
		$today = strtotime(date('Y-m-d', time()));
        if (!empty($start_date)) {
            //检查日期是否有效
            list($y, $m, $d) = explode('-', $start_date);
            if (checkdate($m, $d, $y)) {
                $pram["start_date"] = strtotime($start_date);
            } else {
                $start_date = '';
            }
        }
        if (!empty($end_date)) {
            //检查日期是否有效
            list($y, $m, $d) = explode('-', $end_date);
            if (checkdate($m, $d, $y)) {
                $pram["end_date"] = strtotime($end_date)>$today?$today:strtotime($end_date);
            } else {
                $end_date = '';
            }
        }
        //默认查询当前的数据
        if (empty($start_date) && empty($end_date) || $status == 'yesterday') {
            $start_date = date('Y-m-d', strtotime("-1 day"));
            $end_date = date('Y-m-d',$today);
        }
		if($status_int == 'today'){
			$start_date = date('Y-m-d',$today);
            $end_date = date('Y-m-d', strtotime("+1 day"));
		}
		
		$pram["start_date"] = strtotime($start_date);
		$pram["end_date"] = strtotime($end_date);
		
		$data = D("Income")->getbills($pram);
        $pagebar = new \Think\Page($data['count'], 10);
		foreach($data['list'] as $key=>$value){
			$data['list'][$key]['num'] = $value['basic_success_num']+$value['vip_success_num'];
			$data['list'][$key]['income'] = sprintf('%.2f', $value['money']*($value['proportion']/100));
			$data['list'][$key]['money'] = sprintf('%.2f', $value['money']);
			$data['list'][$key]['user'] = $user_arr[$value['refid']];
		}
		$Income_data = D("Income")->getbills_count($pram);
		//
		
		$this->assign("Income_data", $Income_data);
		$this->assign("data", $data['list']);
        $this->assign("page", $pagebar->show());
		$this->assign("count", $data['count']);
		$this->assign("agent", $user_arr);
		$this->assign("status", $status);
		$this->assign("agent_id", $agent_id);
		$this->assign("start_date", $start_date);
        $this->assign("end_date", $end_date);
        $this->display();
	}
	/**
	* 员工收益
	**/
	public function staff(){
		//获取昨日时间
		$bills_date=strtotime(date('Y-m-d', strtotime("-1 day")));
		//
		$member = $this->USER;
		//获取其所有下级的收益
		$total_income = M('member')->where(['pid'=>session('uid')])->sum('total_income');
		//获取所有下级
		$sub_user_ret = M('member')->field('uid,level,proportion')->where(['pid'=>session('uid')])->select();
		$sub_uid = [];
		$sub_info = [];
		foreach($sub_user_ret as $value){
			$sub_uid[] = $value['uid'];
			$sub_info[$value['uid']]=[
										'level' => $value['level'],
										'proportion' => $value['proportion'],
									];
		}
		//获取今日充值
		$today_data = D("Income")->Income_today_count(session('uid'),$member['level']);
		//var_dump(session('uid'));
		//var_dump($today_data);
		$sub_today_income = 0;
		if(count($sub_uid)>0){
			foreach($sub_uid as $value){
				$sub_today_data = D("Income")->Income_today_count($value,$sub_info[$value]['level']);
				$sub_today_income += $sub_today_data*($sub_info[$value]['proportion']/100);
			}
		}
		
		
		//获取昨日收益
		$yesterday_data = M('member_bills')->field('money,income')->where(['refid'=>session('uid'),'bills_date'=>strtotime(date('Y-m-d', strtotime("-1 day")))])->find();
		//获取昨日下级分成
		$sub_yesterday = 0;
		if(count($sub_uid)>0){
			$sub_yesterday = M('member_bills')->where(['refid'=>['in',$sub_uid],'bills_date'=>strtotime(date('Y-m-d', strtotime("-1 day")))])->sum('income');
		}
		
		$data['total_money']=sprintf('%.2f', $member['total_money']);//累计充值
		$data['money']=sprintf('%.2f', $member['total_income']-$total_income);//累计分成
		$data['yesterday_money']=sprintf('%.2f', $yesterday_data['money']);
		$data['yesterday_income']=sprintf('%.2f', $yesterday_data['income']-$sub_yesterday);//昨日分成
		$data['today_money']=sprintf('%.2f', $today_data);//今日充值
		$data['today_income']=sprintf('%.2f', ($today_data*$member['proportion']/100)-$sub_today_income);//今日分成
		
		
		//获取月账单
		$reg_month = strtotime(date('Y-m',$this->USER['t']));//获取用户注册月份
		$month_num = (date("Y")-date("Y",$reg_month))*12+(date("m")-date("m",$reg_month));//获取用户注册到现在几个月
		if($month_num == 0){
			$month_num = 1;
		}else if($month_num > 20){
			$month_num = 20;
		}
		//获取当前月
		$now_month = date("Y-m-d H:i:s");
		$data['list'] = [];
		//员工月份统计
		$cache_name ='staff_month_';
		for($i=0;$i<$month_num;$i++){
			$start_i = $i;
			$end_i = $i-1;
			$start = date('Y-m',strtotime("$now_month-$start_i month"));
			$end = date('Y-m',strtotime("$now_month-$end_i month"));
			
			$staff_month = '';
			if($i>0){
				$cache_staff = S($cache_name.$this->USER['uid'].'_'.strtotime($start));
				if(!empty($cache_staff)){
					$staff_month = $cache_staff;
				}
			}
			if(empty($staff_month)){
				$money_count=D("Income")->Income_users_cont($this->USER['uid'],strtotime($start),strtotime($end));
				if(count($sub_uid)>0){
					$pay_count = D("Income")->Income_users_cont($sub_uid,strtotime($start),strtotime($end));
				}else{
					$pay_count['income'] = 0;
				}
				$data['list'][$start]=[
										'total_money'	=> sprintf('%.2f', $money_count['money']),
										'total_income'	=> sprintf('%.2f', $money_count['income']),
										'proportion'	=> $this->USER['proportion'],
										'pay_money'		=> sprintf('%.2f', $pay_count['income']),
										'income'		=> sprintf('%.2f', $money_count['income']-$pay_count['income']),
										];
				S($cache_name.$this->USER['uid'].'_'.strtotime($start),$data['list'][$start]);
			}else{
				$data['list'][$start]=$staff_month;
			}
		
		}
		$this->assign("count" , $month_num);
		$this->assign("today_month" , date('Y-m'));
		$this->assign("data" , $data);
		$this->display();
	}
    /**
     *  个人资料
     */
    public function index(){
		$prefix = C("DB_PREFIX");
        $member = M("member")->field("{$prefix}member.*,{$prefix}auth_group.title")
                ->join("{$prefix}auth_group ON {$prefix}auth_group.id = {$prefix}member.level")
                ->where(['uid'=>session('uid')])
                ->find();
		$this->assign("member" , $member);
        $this->display();
    }
    
    
}
